import axios from 'axios'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import router from '@/router'
<<<<<<< HEAD

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.DEV ? '/api' : (import.meta.env.VITE_APP_BASE_API || 'http://localhost:8082/api'),
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
=======
import { getApiConfig, HTTP_STATUS, BUSINESS_ERROR_CODES, getErrorMessage } from '@/config/api'

// 获取API配置
const apiConfig = getApiConfig()

// 创建axios实例
const service = axios.create({
  baseURL: apiConfig.baseURL,
  timeout: apiConfig.timeout,
  withCredentials: apiConfig.withCredentials,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
>>>>>>> c61637f (所有前后端正常登录)
  }
})

let loadingInstance = null

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 开发环境下打印请求信息
    if (import.meta.env.DEV) {
      console.log('发送请求:', config.method?.toUpperCase(), config.url, config.data)
    }

    // 显示loading
    if (config.showLoading !== false) {
      loadingInstance = ElLoading.service({
        lock: true,
        text: '请稍候...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    }

    // 添加token
<<<<<<< HEAD
    const token = localStorage.getItem('token')
=======
    const token = localStorage.getItem('merchant_token')
>>>>>>> c61637f (所有前后端正常登录)
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }

    // 添加时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }

<<<<<<< HEAD
=======
    // 添加请求ID用于追踪和重试
    config.requestId = `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

    // 检查网络连接
    if (!navigator.onLine) {
      if (loadingInstance) {
        loadingInstance.close()
      }
      return Promise.reject(new Error('网络连接已断开，请检查网络设置'))
    }

>>>>>>> c61637f (所有前后端正常登录)
    return config
  },
  error => {
    if (import.meta.env.DEV) {
      console.error('请求拦截器错误:', error)
    }
    if (loadingInstance) {
      loadingInstance.close()
    }
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (loadingInstance) {
      loadingInstance.close()
    }

    const res = response.data

    // 如果返回的状态码不是200，说明接口有问题
<<<<<<< HEAD
    if (res.code && res.code !== 200) {
      ElMessage.error(res.message || '请求失败')

      // 401: 未授权，需要重新登录
      if (res.code === 401) {
        ElMessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          router.push('/login')
        })
      }

      return Promise.reject(new Error(res.message || '请求失败'))
=======
    if (res.code && res.code !== HTTP_STATUS.OK) {
      const errorMessage = getErrorMessage(res.errorCode, res.message || '请求失败')

      // 只在非静默模式下显示错误消息
      if (response.config?.showError !== false) {
        ElMessage.error(errorMessage)
      }

      // 401: 未授权，需要重新登录
      if (res.code === HTTP_STATUS.UNAUTHORIZED || res.errorCode === BUSINESS_ERROR_CODES.TOKEN_EXPIRED) {
        if (!window.location.pathname.includes('/login')) {
          ElMessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            localStorage.removeItem('merchant_token')
            localStorage.removeItem('merchant_info')
            localStorage.removeItem('merchant_status')
            router.push('/login')
          }).catch(() => {
            // 用户取消登录
          })
        }
      }

      // 创建增强的错误对象
      const enhancedError = new Error(errorMessage)
      enhancedError.code = res.code
      enhancedError.errorCode = res.errorCode
      enhancedError.data = res.data
      enhancedError.timestamp = new Date().toISOString()

      return Promise.reject(enhancedError)
>>>>>>> c61637f (所有前后端正常登录)
    }

    // 返回数据
    return res
  },
  error => {
    if (loadingInstance) {
      loadingInstance.close()
    }

    // 开发环境下打印错误详情
    if (import.meta.env.DEV) {
      console.error('响应拦截器错误:', error)
      console.error('错误详情:', {
        message: error.message,
        response: error.response,
        request: error.request,
        config: error.config
      })
    }

    let message = '请求失败'

    if (error.response) {
      const { status, data } = error.response
      if (import.meta.env.DEV) {
        console.error('响应错误:', status, data)
      }

      switch (status) {
<<<<<<< HEAD
        case 400:
          message = data.message || '请求参数错误'
          break
        case 401:
          message = data.message || '登录状态已过期，请重新登录'
          // 只有在非登录页面时才跳转
          if (!window.location.pathname.includes('/login')) {
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            router.push('/login')
          }
          break
        case 403:
          message = '没有权限访问该资源'
          break
        case 404:
          message = '请求的资源不存在'
          break
        case 500:
          message = '服务器内部错误'
=======
        case HTTP_STATUS.BAD_REQUEST:
          message = getErrorMessage(data.errorCode, data.message || '请求参数错误')
          break
        case HTTP_STATUS.UNAUTHORIZED:
          message = getErrorMessage(BUSINESS_ERROR_CODES.TOKEN_EXPIRED, data.message || '登录状态已过期，请重新登录')
          // 只有在非登录页面时才跳转
          if (!window.location.pathname.includes('/login')) {
            localStorage.removeItem('merchant_token')
            localStorage.removeItem('merchant_info')
            localStorage.removeItem('merchant_status')
            router.push('/login')
          }
          break
        case HTTP_STATUS.FORBIDDEN:
          message = getErrorMessage(BUSINESS_ERROR_CODES.FORBIDDEN, '没有权限访问该资源')
          break
        case HTTP_STATUS.NOT_FOUND:
          message = getErrorMessage(BUSINESS_ERROR_CODES.NOT_FOUND, '请求的资源不存在')
          break
        case HTTP_STATUS.UNPROCESSABLE_ENTITY:
          message = getErrorMessage(data.errorCode, data.message || '数据验证失败')
          break
        case HTTP_STATUS.INTERNAL_SERVER_ERROR:
          message = '服务器内部错误，请稍后重试'
          break
        case HTTP_STATUS.BAD_GATEWAY:
          message = '网关错误，请稍后重试'
          break
        case HTTP_STATUS.SERVICE_UNAVAILABLE:
          message = '服务暂时不可用，请稍后重试'
>>>>>>> c61637f (所有前后端正常登录)
          break
        default:
          message = data.message || `请求失败 (${status})`
      }
    } else if (error.code === 'ECONNABORTED') {
      message = '请求超时，请稍后重试'
    } else if (error.message.includes('Network Error')) {
      message = '网络连接失败，请检查网络'
    }

<<<<<<< HEAD
    ElMessage.error(message)
    return Promise.reject(error)
=======
    // 创建增强的错误对象
    const enhancedError = new Error(message)
    enhancedError.code = error.code || 'UNKNOWN_ERROR'
    enhancedError.config = error.config
    enhancedError.response = error.response
    enhancedError.request = error.request
    enhancedError.timestamp = new Date().toISOString()

    // 简单的错误处理，暂时移除自动重试功能

    // 只在非静默模式下显示错误消息
    if (error.config?.showError !== false) {
      ElMessage.error(message)
    }

    return Promise.reject(enhancedError)
>>>>>>> c61637f (所有前后端正常登录)
  }
)

// 封装GET请求
export function get(url, params, config = {}) {
  return service.get(url, { params, ...config })
}

// 封装POST请求
export function post(url, data, config = {}) {
  return service.post(url, data, config)
}

// 封装PUT请求
export function put(url, data, config = {}) {
  return service.put(url, data, config)
}

// 封装DELETE请求
export function del(url, params, config = {}) {
  return service.delete(url, { params, ...config })
}

<<<<<<< HEAD
// 导出axios实例
export default service 
=======
// 文件上传
export function uploadFile(url, file, config = {}) {
  const formData = new FormData()
  formData.append('file', file)

  return service.post(url, formData, {
    ...config,
    headers: {
      'Content-Type': 'multipart/form-data',
      ...config.headers
    },
    timeout: 60000, // 文件上传超时时间更长
    showLoading: config.showLoading !== false,
    loadingText: config.loadingText || '上传中...'
  })
}

// 批量上传文件
export function uploadFiles(url, files, config = {}) {
  const formData = new FormData()
  files.forEach((file, index) => {
    formData.append(`files[${index}]`, file)
  })

  return service.post(url, formData, {
    ...config,
    headers: {
      'Content-Type': 'multipart/form-data',
      ...config.headers
    },
    timeout: 120000, // 批量上传超时时间更长
    showLoading: config.showLoading !== false,
    loadingText: config.loadingText || '批量上传中...'
  })
}

// 下载文件
export function downloadFile(url, params = {}, config = {}) {
  return service.get(url, {
    params,
    responseType: 'blob',
    showLoading: config.showLoading !== false,
    loadingText: config.loadingText || '下载中...',
    ...config
  })
}

// 批量请求
export async function batchRequest(requests, options = {}) {
  const { concurrent = 3, showProgress = false } = options
  const results = []
  const errors = []

  // 分批处理请求
  for (let i = 0; i < requests.length; i += concurrent) {
    const batch = requests.slice(i, i + concurrent)

    try {
      const batchResults = await Promise.allSettled(
        batch.map(req => typeof req === 'function' ? req() : req)
      )

      batchResults.forEach((result, index) => {
        if (result.status === 'fulfilled') {
          results[i + index] = result.value
        } else {
          errors[i + index] = result.reason
        }
      })

      // 显示进度
      if (showProgress) {
        const progress = Math.round(((i + batch.length) / requests.length) * 100)
        console.log(`批量请求进度: ${progress}%`)
      }
    } catch (error) {
      console.error('批量请求错误:', error)
    }
  }

  return { results, errors }
}

// 请求重试工具（暂时禁用）
export async function requestWithRetry(requestFn, options = {}) {
  // 简单重试实现
  const { maxRetries = 3, delay = 1000 } = options
  let lastError

  for (let i = 0; i <= maxRetries; i++) {
    try {
      return await requestFn()
    } catch (error) {
      lastError = error
      if (i < maxRetries) {
        await new Promise(resolve => setTimeout(resolve, delay))
      }
    }
  }

  throw lastError
}

// 导出axios实例
export default service
>>>>>>> c61637f (所有前后端正常登录)
